//var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

var http = require('../../../../service/http.js');//请求类
var util = require('../../../../utils/util.js');//工具类
var rd_session = '';

const app = getApp();
Page({
  data: {
    //-----------页面加载--------------------------------
    showPage: false,//是否展示页面

    //------------当前页名称-----------------------------
    pageName: 'orders',
    tabs: [
      { name: "全部", status: '' },
      { name: "待付款", status: '10' },
      { name: "待发货", status: '20' },
      { name: "待收货", status: '30' },
      { name: "已完成", status: '50' },
    ],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    sliderWidth:60,
    //-----------订单列表相关参数------------------------
    pageNo:1,//请求商品页数
    total:0,//分页总页数，
    status:10, //单个订单订单状态
    orders:[], //所有订单[]
    statusOri: '',//根据 statusOri 查询多种订单
    orderId:'',//订单id
    //----------店铺相关-------------------------
    shopName: '', //店铺名称
  },
  onLoad: function (options) {
    let that = this;
    if (options.checkOrders == '1'){//通过模板消息进入
      app.checkSession();
      let checkSessionTask = setInterval(function(){
        let isAuthorization = app.data.isAuthorization;
        if (isAuthorization === true || isAuthorization === false){
          clearInterval(checkSessionTask);
          if (!isAuthorization){
            console.log("登录已过期，需要重新登录");
            wx.showToast({
              title: '您的登录已过期，需要重新登录',
              icon: 'none',
              duration:1000,
              mask: true
            })
            setTimeout(function(){
              that.backToHome();//回到首页
            },1000);
          }
        }
      },10)
    }
    that.showList(options);//加载订单列表
  },
  //-------登陆动画-------------------
  loginAnimation: function () {
    app.loginAnimation();
    this.setData({
      animationData: app.data.animationData,
      isAuthorization: app.data.isAuthorization
    })
  },
  //-----------------------关闭登陆动画---------------------------------
  closeLoginAnimation: function (e) {
    console.log(e);
    let that = this;
    app.closeLoginAnimation(e);
    that.setData({
      animationData: app.data.animationData,
      isAuthorization: app.data.isAuthorization
    })
    if (that.data.isAuthorization){//登录成功
      that.onLoad();
    }
  },
  //-----------------------展示订单列表---------------------------------
  showList: function (options){
    console.log('展示订单列表');
    let that = this;
    console.log(options);

    that.selectByOrderStatus(options);//根据订单状态查询订单列表

    let activeIndex = 0;
    let statusOri = 0;
    if (options) {//如果orderIndex参数不为空则为支付模板消息入口进入
      activeIndex = options.activeIndex
      statusOri = options.statusOri
    }
    that.setData({
      activeIndex: activeIndex || 0,
      statusOri: statusOri || ''
    })
   // that.data.activeIndex = activeIndex;//设置展示内容
    console.log("activeIndex" + activeIndex);
    //获取用户信息设置，根据orderIndex设置tab位置
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderWidth: res.windowWidth / 5,
          sliderLeft: (res.windowWidth / that.data.tabs.length - that.data.sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * activeIndex,
        });
      }
    });
    console.log("orders---onLoad");
  },
  onShow:function(){
    rd_session = wx.getStorageSync('rd_session');
    console.log("查询当前订单类型=" + this.data.statusOri);
    this.setData({
      shopName: app.data.shopName, //店铺名称
    })
  },


  tabClick: function (e) {//tab点击事件
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id || 0
    });
  },
  orderDetial:function(e){//根据id 产看订单详情
    console.log('orderDetial');
    console.log(e);
    let orderId = e.currentTarget.dataset.orderid;
    
    wx.navigateTo({
      url: '/pages/product/pages/order/order?orderId=' + orderId,
      success: function(res) {
        console.log('跳转到orderjs');
      }
    }) 
  
  },
  cancelOrder:function(e){//关闭订单
    let orderId = e.currentTarget.dataset.orderid;
    let that = this;
    console.log("orderId"+orderId);
    wx.showModal({
      title: '',
      content: '确定要取消该订单么？',
      cancelText:'我再想想',
      confirmText:'确定',
      success:function(res){
        if (res.confirm) {
          http.getReq('/weixin/getOrder/closeOrder', {
            orderId: orderId
          }, function (rr) {
            if (rr.ret) {

              util.showToast('订单已取消', 1000, 'none', function () { 
                that.setData({//取消订单后跳转至全部订单
                  statusOri: '',
                  activeIndex: '',
                })
                that.onPullDownRefresh();
              });
           
            } else {
              app.connectionTimeout('订单未同步');
            }
          });
         
        }
      }
    })
  },

  selectByOrderStatus:function(e){//根据订单状态查询订单列表
    
    let that = this;
    console.log(e);
    //页面暂不展示
    that.setData({
      showPage: false,//是否展示订单内容
    })
    let statusOri = that.data.statusOri;
    let activeIndex = that.data.activeIndex;
    console.log("订单状态statusOri=" + statusOri);
    if (e || ''){
      //从onload()外部加载方法 所带参数e.statusOri && e.activeIndex 
      if (e.statusOri && e.activeIndex) {
        statusOri = e.statusOri;//根据 statusOri 查询多种订单
        activeIndex = e.activeIndex;//tab下标
      }
      //从订单页面点击加载-------------------------------------------------
      else if (e.currentTarget) {
        statusOri = e.currentTarget.dataset.status;//-订单状态参数
        activeIndex = e.currentTarget.id //tab-id
      }
    }
    
    
    //获取用户信息设置，根据orderIndex设置tab位置
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderOffset: res.windowWidth / that.data.tabs.length * activeIndex,
        });
      }
    });

    //---------------------设置tab位置-----------------------------------
    this.setData({
      statusOri: statusOri || '',//距离屏幕左侧距离
      activeIndex: activeIndex || 0 //tab-id
    });

    
    //初始化商品列表
    let [pageNo, orders, total] = [1,[],0];
    that.setData({
      orders: orders,
      pageNo:1
    })
    
    
    //---------------------------请求订单列表-------------------------------  
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function(res) {

        http.getReq('/weixin/getOrder/list', {
          rdSession: rd_session,
          pageNo: pageNo,
          pageSize: app.data.pageSize,
          statusOri: statusOri
        }, function (res) {
          total = res.total;//分页总页数
          orders = res.orders;//查询返回的所有订单
          console.log("返回分页总页数" + res.total);
          console.log(orders);
          //设置分页总数和订单
          that.setData({
            total: total,
            orders: orders,
            showPage: true,//加载后展示订单内容
          })
          wx.hideLoading();
          wx.stopPullDownRefresh(e)
        });

      }
    })
  },
  onPullDownRefresh: function () {//下拉刷新
    console.log('下拉刷新');
    let that = this;
    that.selectByOrderStatus();
  },
  backToHome:function(e){
    app.backToHome(this);
  },
  onReachBottom: function (e) {//监听页面到底 分页加载商品
    let that = this;
    let [pageNo, total, statusOri] = [that.data.pageNo, that.data.total, that.data.statusOri];
    //-----------判断是否小于分页总数------------------------
    if (pageNo < total) {
        pageNo = pageNo + 1;
        console.log("发送分页请求");
        
        let orders = that.data.orders;//目前的商品列表
        wx.showLoading({
          title: '加载中',
          success: function (e) {
            http.getReq('/weixin/getOrder/list', {
              rdSession: rd_session,
              pageNo: pageNo,
              pageSize: app.data.pageSize,
              statusOri: statusOri
            }, function (res) {
              total = res.total;//分页总页数
              let newList = res.orders;//查询返回的所有订单
              console.log("返回分页总页数" + res.total);
              console.log(orders);
              console.log("newList.length" + newList.length);
              if (newList.length > 0) {
                orders.push(...newList);//追加数组
              } else {//商品长度为0 没有更多商品了
                console.log('没有更多商品了')
              }
              that.setData({
                orders: orders,
                total: total,
                pageNo: pageNo
              })
              console.log("当前页" + pageNo);
              console.log("请求返回订单列表长度" + that.data.orders.length);
              wx.hideLoading();
            });
           
          }
        })
    }
  },
  //确认收货
  finishOrder:function(e){
    console.log(e);
    let orderId = e.currentTarget.dataset.orderid;
    let that = this;
    console.log("orderId" + orderId);
    wx.showModal({
      title: '',
      content: '确定收到货物了么？',
      cancelText: '取消',
      confirmText: '确定',
      success: function (res) {
        if (res.confirm) {
          http.getReq('/weixin/getOrder/finishOrder', {
            orderId: orderId
          }, function (res) {
            console.log(res);
            if (res.ret) {
              util.showToast('确认收货成功', 1000, 'none', function () { 
                that.onPullDownRefresh();
              });
            }
          });
        }
      }
    })
  },
  getFormId: function (e) {
    console.log(e);
    app.getFormId(e);
  },
  
  //一键复制订单号：
  copyOrderId: function (e) {
    app.copyOrderId(e);
  },
});